package com.fyy.netty.chapter01.c1;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * @Author fyy
 * @Description 异步阻塞
 * @Date 2021/4/25 17:06
 */
@Slf4j
public class AIOFileChannel {

    public static void main(String[] args) throws IOException {
        try (AsynchronousFileChannel channel = AsynchronousFileChannel.open(Paths.get("F:\\data.txt"), StandardOpenOption.READ)) {
            ByteBuffer buffer = ByteBuffer.allocate(1);
            int count = 0;
            /**
             * @param buffer ByteBuffer
             * @param 0 读取的起始位置
             * @param buffer 附件
             * @param CompletionHandler 回调对象
             */
            while (count < 10){
                count += 1;
                channel.read(buffer, count, buffer, new CompletionHandler<Integer, ByteBuffer>() {
                    //读取成功
                    @Override
                    public void completed(Integer result, ByteBuffer attachment) {
                        Thread.currentThread().setName("f");
                        attachment.flip();
                        log.info("读取的内容：{}", StandardCharsets.UTF_8.decode(attachment));
                        attachment.clear();
                    }
                    //读取失败
                    @Override
                    public void failed(Throwable exc, ByteBuffer attachment) {
                        log.info("读取错误:{}",exc.getMessage());
                    }
                });
            }

        } catch (IOException e) {
            log.info("读取错误：{}",e.getMessage());
        }
        System.in.read();
    }

}
